package com.cencus.controller;

import com.cencus.domain.Code;
import com.cencus.domain.Photo;
import com.cencus.service.PhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.IOException;
import java.nio.file.*;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/api/photos")
public class PhotoController {

    @Autowired
    private PhotoService photoService;

    @PostMapping
    public ResponseEntity<String> uploadPhoto(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is empty");
        }

        try {
            // Save the file locally
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            Path filePath = Paths.get("uploads", fileName);
            Files.createDirectories(filePath.getParent());
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // Save file info to the database
            Photo photo = new Photo();
            photo.setId(UUID.randomUUID().toString());
            String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path("/api/photos/")
                    .path(fileName)
                    .toUriString();
            photo.setResourceUrl(fileDownloadUri);
            photo.setUploadTime(new Date());
            // Set expiryTime to 30 days from now as an example
            photo.setExpiryTime(new Date(System.currentTimeMillis() + 30L * 24 * 60 * 60 * 1000));
            photo.setExpired(false);
            photo.setDaysExpired(0);

            photoService.savePhoto(photo);

            return ResponseEntity.status(HttpStatus.OK).body("File uploaded successfully: " + fileName);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file");
        }
    }

    @GetMapping
    public Result getAllPhotos() {
        return new Result(Code.OK, photoService.getAllPhotos());
    }
}
